public class Publisher implements Runnable {
    private String name;
    private String[] messages;
    private Announcements announcements;
    private int index;

    public Publisher(String name, String[] messages, Announcements announcements) {
        this.name = name;
        this.messages = messages;
        this.announcements = announcements;
        this.index = 0;
    }

    public void publish() {
        if (messages != null && index < messages.length) {
            int i = announcements.getCurrentIndex();
            announcements.getData()[i] = name + ": " + messages[index];
            index++;
            System.out.println(name + " published: " + messages[index - 1]);
        }
    }
    @Override
    public void run() {
        while (messages != null && index < messages.length) {
            publish();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        Announcements announcements = new Announcements(10);
        Publisher p1 = new Publisher("P1", new String[]{"6666", "7777", "9999"}, announcements);
        Publisher p2 = new Publisher("P2", new String[]{"hi", "ha", "hello"}, announcements);
        Publisher p3 = new Publisher("P3", new String[]{"aaa", "bbb", "ccc"}, announcements);
        Thread t1 = new Thread(p1);
        Thread t2 = new Thread(p2);
        Thread t3 = new Thread(p3);
        t1.start();
        t2.start();
        t3.start();
        try {
            t1.join();
            t2.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        announcements.showInfo();
    }

}
